﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;

namespace K9Nano.Domain
{
    public static class EfCoreExtensions
    {
        public static int HardDelete<TEntity>(this IQueryable<TEntity> query, int batchSize = 200) where TEntity : class
        {
            return query.Where(x => true).Delete(x => x.BatchSize = batchSize);
        }

        public static Task<int> HardDeleteAsync<TEntity>(this IQueryable<TEntity> query,
            int batchSize = 200,
            CancellationToken cancellation = default) where TEntity : class
        {
            return query.Where(x => true).DeleteAsync(x => x.BatchSize = batchSize, cancellation);
        }

        public static int HardDelete<TEntity, TKey>(this DbSet<TEntity> table, TKey id)
            where TEntity : class, IEntity<TKey>
            where TKey : IEquatable<TKey>
        {
            return table.Where(x => x.Id.Equals(id)).Delete();
        }

        public static int HardDelete<TEntity>(this DbSet<TEntity> table, long id)
            where TEntity : class, IEntity<long>
        {
            return table.Where(x => x.Id == id).Delete();
        }

        public static Task<int> HardDeleteAsync<TEntity, TKey>(this DbSet<TEntity> table, TKey id,
            CancellationToken cancellation = default) where TEntity : Entity
        {
            return table.Where(x => x.Id.Equals(id)).DeleteAsync(cancellation);
        }

        public static Task<int> HardDeleteAsync<TEntity>(this DbSet<TEntity> table, long id,
            CancellationToken cancellation = default) where TEntity : Entity
        {
            return table.Where(x => x.Id == id).DeleteAsync(cancellation);
        }
    }
}